﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_TiepNhan_NhapBoXungHoSo
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Dim _HuyenId As Integer
#Region "Event for control "
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            If Session("UserId") Is Nothing Then
                Response.Redirect("~/Login.aspx")
            End If
            hidCurHuyenId.Value = Session("HuyenId")
            _HuyenId = Session("HuyenId")
            Load2Grid()
            LoadModeFrom()
        End If
    End Sub
    Protected Sub Load2Grid()
        Using _data As New VSEntities
            'load CertifiedProvinderOrg by DeptCertifieds
            Dim _l = (From q In _data.DeptCertifieds Where q.ProvinceId = hidCurHuyenId.Value Order By q.Sort Select q).ToList

            With ddlCertifiedProviderOrg
                .DataSource = _l
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            'load CertifiedDeptName by DeptCertifieds
            With ddlCertifiedDeptName
                .DataSource = _l
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            Dim _DoViCap = (From q In _data.DeptCertifieds Where q.ProvinceId = hidCurHuyenId.Value And q.Code = "001" Order By q.Sort Select q.Name).FirstOrDefault
            Dim _PhongBanCap = (From q In _data.DeptCertifieds Where q.ProvinceId = hidCurHuyenId.Value And q.Code = "002" Order By q.Sort Select q.Name).FirstOrDefault
            'Đơn vị cấp            
            ddlCertifiedProviderOrg.SelectedValue = _DoViCap
            'Phòng ban cấp
            ddlCertifiedDeptName.SelectedValue = _PhongBanCap

            With ddlSoLanCapDoi
                .DataSource = Enumerable.Range(1, 20)
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'Tỉnh
            Dim TinhDiaDiemKD = (From q In _data.Provinces Where q.ParentId = 0 Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlTinhDiaDiemKD
                .DataSource = TinhDiaDiemKD
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'huyen ho khau
            'tinh hien tai theo huyện
            Dim p = (From q In _data.Provinces Where q.Id = _HuyenId Select q).FirstOrDefault
            Dim huyenDiaDiemKD = (From q In _data.Provinces Where q.ParentId = p.ParentId Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlHuyenDiaDiemKD
                .DataSource = huyenDiaDiemKD
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'xa thi tran hien tai
            Dim xaDiaDiemKD = (From q In _data.Provinces Where q.ParentId = _HuyenId Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlXaThiTranDiaDiemKD
                .DataSource = xaDiaDiemKD
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With

            'tinh ho khau
            Dim TinhHoKhau = (From q In _data.Provinces Where q.ParentId = 0 Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlTinhHoKhau
                .DataSource = TinhHoKhau
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'huyen ho khau
            '171 tinh an giang
            Dim huyenHoKhau = (From q In _data.Provinces Where q.ParentId = p.ParentId Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlHuyenHoKhau
                .DataSource = huyenHoKhau
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'xa thi tran hien tai
            Dim xaHoKhau = (From q In _data.Provinces Where q.ParentId = _HuyenId Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlXaThiTranHoKhau
                .DataSource = xaHoKhau
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With

            'tinh hien tai
            Dim TinhHienTai = (From q In _data.Provinces Where q.ParentId = 0 Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlTinhHienTai
                .DataSource = TinhHienTai
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'huyen ho khau
            '171 tinh an giang
            Dim huyenHienTai = (From q In _data.Provinces Where q.ParentId = p.ParentId Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlHuyenHienTai
                .DataSource = huyenHienTai
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'xa thi tran hien tai
            Dim xaHienTai = (From q In _data.Provinces Where q.ParentId = _HuyenId Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlXaThiTranHienTai
                .DataSource = xaHienTai
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With

            'NGanh nghe
            Dim linhvuc = (From q In _data.BusinessFields Order By q.Name Select New With {.Id = q.Id, .Name = q.Name}).ToList
            With ddlBusinessField
                .DataSource = linhvuc
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With

            'dan toc
            Dim dantoc = (From q In _data.Citizens Order By q.Name Select New With {.Id = q.Name, .Name = q.Name}).ToList
            With ddlCitizen
                .DataSource = dantoc
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With

            'quoc gia
            Dim Country = (From q In _data.Countries Order By q.Name Select New With {.Id = q.Name, .Name = q.Name}).ToList
            With ddlCountry
                .DataSource = Country
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With

            'dong vi cap giay chung nhan CMND
            Dim DeptCertified = (From q In _data.DeptIdentifies Order By q.Name Select New With {.Id = q.Name, .Name = q.Name}).ToList
            With ddlDeptCertified
                .DataSource = DeptCertified
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With

            'dong vi cap giay chung nhan khac
            Dim d = (From q In _data.DeptIdentifies Order By q.Name Select New With {.Id = q.Id, .Name = q.Name}).ToList
            With ddlOthersPaper_NoiCap
                .DataSource = d
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'giấy tờ khác
            Dim CertifiedPaperDict = (From q In _data.CertifiedPaperDicts Order By q.Name Select New With {.Id = q.Id, .Name = q.Name}).ToList
            With ddlOthersPaper
                .DataSource = CertifiedPaperDict
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'thanh phan ho so
            Dim lstThanhPhanHoSo = (From q In _data.ThanhPhanHoSoes Order By q.IsDefault Descending, q.TenHoSo Select q).ToList
            Dim strKey_Name() As String = {"Id", "MaHoSo", "IsDefault"}
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = lstThanhPhanHoSo
                .DataBind()
            End With

        End Using
    End Sub
    Protected Sub LoadModeFrom()
        Using data As New VSEntities
            txtBizName.Text = "HỘ KINH DOANH "
            'load dân tộc
            ddlCitizen.SelectedValue = "Kinh"
            'load quốc tịch
            ddlCountry.SelectedValue = "Việt Nam"
            'load nơi cấp CMND
            ddlDeptCertified.SelectedValue = "Công an tỉnh An Giang"

            Dim p = (From q In data.Provinces Where q.Id = _HuyenId Select q).FirstOrDefault
            'load tỉnh
            ddlTinhHoKhau.SelectedValue = p.ParentId 'tỉnh của user hiện tại
            hidHuyenHoKhau.Text = p.ParentId 'tỉnh của user hiện tại
            'load huyen ho khau
            ddlHuyenHoKhau.SelectedValue = _HuyenId 'huyên hiên tại User quản lý
            hidHuyenHoKhau.Text = hidCurHuyenId.Value
            'load tinh hien tai
            ddlTinhHienTai.SelectedValue = p.ParentId 'tỉnh của user hiện tại
            hidHuyenHienTai.Text = p.ParentId 'tỉnh của user hiện tại
            'load huyen hien tai
            ddlHuyenHienTai.SelectedValue = _HuyenId 'huyen hien tai user quan ly
            hidHuyenHienTai.Text = hidCurHuyenId.Value
            'load tinh dia diem kinh doanh
            ddlTinhDiaDiemKD.SelectedValue = p.ParentId 'tỉnh của user hiện tại
            hidHuyenDiaDiemKD.Text = p.ParentId 'tỉnh của user hiện tại
            'load huyen dia diem kinh doanh
            ddlHuyenDiaDiemKD.SelectedValue = _HuyenId 'huyen hien tai user quan ly
            hidHuyenDiaDiemKD.Text = _HuyenId
        End Using

    End Sub
#Region "Sub InsertCertified "
    Protected Sub InsertCertified()
        Using _data As New VSEntities
            Dim p As New VSModel.CertifiedHousehold
            Try
                'Thông tin chung
                p.CertifiedStatus = "M" 'cấp mới
                p.CertifiedUp_Time = 0 'cấp mới = 0

                p.CertifiedCode = txtCertifiedCode.Text.Trim() ' số GCN
                p.CertifiedDate = StringToDate(txtCertifiedDate.Text) 'Ngày cấp GCN

                p.CertifiedUp_Date = Now 'ngay nhap ho so
                'thong tin ca nhan
                p.Ow_Name = txtOwRepresentative.Text 'Họ tên
                p.Ow_Sex = rdlSex.SelectedValue 'giới tính
                p.Ow_BirthDate = txtOwDateOfBirth.Text 'ngày tháng năm sinh
                p.Ow_National_ID = ddlCitizen.Text 'dân tộc
                p.Ow_Nationality_ID = ddlCountry.Text 'Quốc tịch
                p.Ow_CardID = txtOwCardId.Text 'Số CMND
                p.Ow_CardDate = StringToDate(txtOwCardDate.Text) 'Ngày cấp
                p.Ow_Provider_ID = ddlDeptCertified.Text 'Nơi cấp
                'giay to khac
                p.Ow_Doc_ID = ddlOthersPaper.SelectedValue 'Giấy tờ khác
                p.Ow_DocCode = txtOtherPaperCode.Text 'Mã số
                p.Ow_DocDate = StringToDate(txtOthersPaperDateIssue.Text.Trim()) 'Ngày cấp
                p.Ow_DocOffiCertifiedID = ddlOthersPaper_NoiCap.SelectedValue 'Nơi cấp
                'Thông tin hộ kinh doanh: 
                p.Biz_VietName = txtBizName.Text.Trim() 'Tên hộ kinh doanh
                p.Ow_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Ow_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Ow_Email = txtOw_Email.Text.Trim() 'Email
                p.Ow_WebSite = txtOw_WebSite.Text.Trim() 'Website
                p.Biz_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Biz_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Biz_Email = txtOw_Email.Text.Trim() 'Email
                p.Biz_Website = txtOw_WebSite.Text.Trim() 'Website
                'linh vưc
                p.LinhVucKinhDoanh = ddlBusinessField.Text 'Lĩnh vực kinh doanh
                p.VonTienMat = txtVonTienMat.Text.Trim()
                p.VonTaiSan = txtVonTaiSan.Text.Trim()
                p.Biz_InvestCapital = txtBiz_InvestCapital.Text.Trim().Replace(".", "") 'vốn kinh doanh
                p.Biz_WordsMoney = txtMoney_string.Text.Trim() 'Tiền viết bằng chữ
                p.Created = Now
                p.Creator = Session("UserName")
                Dim _StatusId As String = TinhTrangHoSo.Hoantat
                If Not _StatusId Is Nothing Then
                    p.StatusId = TinhTrangHoSo.Hoantat ' đã duyệt hồ sơ
                Else
                    p.StatusId = 1
                End If

                p.NguonTao = NguonTao.PhongTCKH
                p.ProvinceId = Session("HuyenId") ' Huyên đang ký kinh doanh
                'luu thong tin bien nhan 
                Dim _HuyenObj = (From q In _data.Provinces Where q.Id = _HuyenId Select q).FirstOrDefault
                If Not _HuyenObj Is Nothing Then
                    Dim _SoNgayTraHoSo As Integer
                    If StringToDateTime(Now.ToString("dd/MM/yyyy"), _HuyenObj.GioBienNhan) > Now Then
                        _SoNgayTraHoSo = _HuyenObj.SoNgayTraHoSo - 1
                    Else
                        _SoNgayTraHoSo = _HuyenObj.SoNgayTraHoSo
                    End If
                    p.NgayTraHoSo = _data.uspGetNumDateDelivery(Now.Date, _SoNgayTraHoSo).FirstOrDefault.DeliveryDate
                End If
                _data.CertifiedHouseholds.AddObject(p)
                _data.SaveChanges()
                p.ParentId = p.CertifiedID ' ho so dang ky lan parentId = CerId
                'Đơn vị cấp
                p.CertifiedProviderOrg = ddlCertifiedProviderOrg.SelectedValue
                'Phòng ban cấp
                p.CertifiedDeptName = ddlCertifiedDeptName.SelectedValue
                _data.SaveChanges()

                'Địa chỉ phường xa huyên
                Dim tht As New VSModel.CertifiedHouseholdAddress
                'thường trú
                tht.CertifiedID = p.CertifiedID
                tht.TypeId = LoaiDiaChi.ThuongTru
                tht.Adress = txtDiaChiHoKhau.Text.Trim()
                tht.TinhId = ddlTinhHoKhau.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                tht.HuyenId = hidHuyenHoKhau.Text
                tht.XaThiTranId = hidXaThiTranHoKhau.Text
                _data.CertifiedHouseholdAddresses.AddObject(tht)
                _data.SaveChanges()
                'luu thuong tru vao CertifiedHousehold
                'lay tien cac truong theo value
                'xa
                Dim jx = (From q In _data.Provinces Where q.Id = hidXaThiTranHoKhau.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jh = (From q In _data.Provinces Where q.Id = hidHuyenHoKhau.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jt = (From q In _data.Provinces Where q.Id = ddlTinhHoKhau.SelectedValue Select q.Title).FirstOrDefault
                p.Ow_Resident = txtDiaChiHoKhau.Text.Trim() & ", " & jx & ", " & jh & ", " & jt
                _data.SaveChanges()
                'tam trú
                Dim tt As New VSModel.CertifiedHouseholdAddress
                tt.CertifiedID = p.CertifiedID
                tt.TypeId = LoaiDiaChi.TamTru
                tt.Adress = txtDiaChiHienTai.Text.Trim()
                tt.TinhId = ddlTinhHienTai.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                tt.HuyenId = hidHuyenHienTai.Text
                tt.XaThiTranId = hidXaThiTranHienTai.Text
                _data.CertifiedHouseholdAddresses.AddObject(tt)
                _data.SaveChanges()
                'luu tam tru vao certifiedhousehold
                'lay tien cac truong theo value
                'xa
                Dim jxt = (From q In _data.Provinces Where q.Id = hidXaThiTranHienTai.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jht = (From q In _data.Provinces Where q.Id = hidHuyenHienTai.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jtt = (From q In _data.Provinces Where q.Id = ddlTinhHienTai.SelectedValue Select q.Title).FirstOrDefault
                p.Ow_Present = txtDiaChiHienTai.Text.Trim() & ", " & jxt & ", " & jht & ", " & jtt
                'địa điểm kinh doanh
                Dim kd As New VSModel.CertifiedHouseholdAddress
                kd.CertifiedID = p.CertifiedID
                kd.TypeId = LoaiDiaChi.DiaDiemKinhDoanh
                kd.Adress = txtBiz_HeadOffice.Text.Trim()
                kd.TinhId = ddlTinhDiaDiemKD.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                kd.HuyenId = hidHuyenDiaDiemKD.Text
                kd.XaThiTranId = hidXaThiTranDiaDiemKD.Text
                _data.CertifiedHouseholdAddresses.AddObject(kd)
                _data.SaveChanges()
                'luu dia diem kinh doanh vao certifiedhousehold
                'lay tien cac truong theo value
                'xa
                Dim jxd = (From q In _data.Provinces Where q.Id = hidXaThiTranDiaDiemKD.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jhd = (From q In _data.Provinces Where q.Id = hidHuyenDiaDiemKD.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jtd = (From q In _data.Provinces Where q.Id = ddlTinhDiaDiemKD.SelectedValue Select q.Title).FirstOrDefault
                p.XaPhuongId = hidXaThiTranDiaDiemKD.Text ' luu XaPhuongId de report

                p.Biz_HeadOffice = txtBiz_HeadOffice.Text.Trim() & ", " & jxd & ", " & jhd & ", " & jtd
                'start ngành nghề

                'lưu thông tin cho CertifiedHouseholdNganhNghe
                Try
                    Dim index As Integer = 0
                    Dim GrossAmount As Integer = 0
                    For i As Integer = 0 To hidRowIndex.Value - 1
                        Dim strMaterialCode As String = ""
                        Dim strMaterialDescription As String = ""
                        Dim strUnit As String = ""
                        Dim intAmount As Integer = 0

                        Dim txtMaterialCode As String = "txtChoice" + i.ToString
                        If Request.Form(txtMaterialCode) <> Nothing AndAlso Request.Form(txtMaterialCode).ToString.Trim() <> "" Then
                            strMaterialCode = Request.Form(txtMaterialCode)
                        End If

                        Dim txtMaterialDescription As String = "txtDescription" + i.ToString
                        If Request.Form(txtMaterialDescription) <> Nothing AndAlso Request.Form(txtMaterialDescription).ToString.Trim() <> "" Then
                            strMaterialDescription = Request.Form(txtMaterialDescription)
                        End If

                        If (strMaterialCode.Trim <> "") Then
                            Dim _NganhNgheId As Integer = (From q In _data.DanhMucNganhNghes Where q.Code = strMaterialCode Select q.Id).FirstOrDefault

                            Dim NganhNgheList As New CertifiedHouseholdNganhNghe
                            NganhNgheList.CertifiedID = p.CertifiedID
                            NganhNgheList.DanhMucNganhNgheID = _NganhNgheId
                            NganhNgheList.Description = strMaterialDescription

                            _data.CertifiedHouseholdNganhNghes.AddObject(NganhNgheList)

                            _data.SaveChanges()
                            index = index + 1

                            'End If
                        End If
                    Next
                Catch ex As Exception
                    Excute_Javascript("Alertbox('Cập nhật ngành nghề thất bại.');", Me.Page, True)
                    Exit Sub
                End Try
                'end ngành nghề
                'start danh sách góp vốn
                'lưu thông tin cho CertifiedHouseholdMember
                Try
                    Dim index As Integer = 0
                    For i As Integer = 0 To hidRowIndex1.Value - 1
                        Dim strTenTV As String = ""
                        Dim strNoiDKHK As String = ""
                        Dim strVonGop As String = ""
                        Dim strTyLeVonGop As String = ""
                        Dim strCMND As String = ""
                        Dim strDescription As String = ""

                        Dim txtTenTV As String = "txtTenTV__" + i.ToString
                        If Request.Form(txtTenTV) <> Nothing AndAlso Request.Form(txtTenTV).ToString.Trim() <> "" Then
                            strTenTV = Request.Form(txtTenTV)
                        End If

                        Dim txtNoiDKHK As String = "txtNoiDKHK__" + i.ToString
                        If Request.Form(txtNoiDKHK) <> Nothing AndAlso Request.Form(txtNoiDKHK).ToString.Trim() <> "" Then
                            strNoiDKHK = Request.Form(txtNoiDKHK)
                        End If
                        Dim txtVonGop As String = "txtVonGop__" + i.ToString
                        If Request.Form(txtTenTV) <> Nothing AndAlso Request.Form(txtVonGop).ToString.Trim() <> "" Then
                            strVonGop = Request.Form(txtVonGop)
                        End If

                        Dim txtTyLeVonGop As String = "txtTyLeVonGop__" + i.ToString
                        If Request.Form(txtTyLeVonGop) <> Nothing AndAlso Request.Form(txtTyLeVonGop).ToString.Trim() <> "" Then
                            strTyLeVonGop = Request.Form(txtTyLeVonGop)
                        End If
                        Dim txtCMND As String = "txtCMND__" + i.ToString
                        If Request.Form(txtCMND) <> Nothing AndAlso Request.Form(txtCMND).ToString.Trim() <> "" Then
                            strCMND = Request.Form(txtCMND)
                        End If

                        Dim txtDescription As String = "txtDescription__" + i.ToString
                        If Request.Form(txtDescription) <> Nothing AndAlso Request.Form(txtDescription).ToString.Trim() <> "" Then
                            strDescription = Request.Form(txtDescription)
                        End If

                        If (strTenTV.Trim <> "") Then

                            Dim member As New CertifiedHouseholdMember
                            member.CertifiedID = p.CertifiedID
                            member.MemberName = strTenTV
                            member.MemberAddress = strNoiDKHK
                            member.MemberValues = strVonGop
                            member.MemberRate = strTyLeVonGop
                            member.MemberCard = strCMND
                            member.MemberDes = strDescription
                            member.MemberOrder = member.Id
                            _data.CertifiedHouseholdMembers.AddObject(member)

                            _data.SaveChanges()
                            index = index + 1

                            'End If
                        End If
                    Next
                Catch ex As Exception
                    Excute_Javascript("Alertbox('Cập nhật danh sách góp vốn thất bại.');", Me.Page, True)
                    Exit Sub
                End Try
                'end danh sách góp vốn

                'start thành phần hồ sơ
                Dim intId As Integer = 0
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        'lay id cua thanh phan ho so
                        intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                        Dim ThanhPhanHoSo As New CertifiedHouseholdThanhPhanHoSo
                        ThanhPhanHoSo.CertifiedID = p.CertifiedID
                        ThanhPhanHoSo.ThanhPhanHoSoId = intId
                        _data.CertifiedHouseholdThanhPhanHoSoes.AddObject(ThanhPhanHoSo)
                        _data.SaveChanges()
                    End If
                Next

                'correct lai Province + HuyenId
                Dim _UserId As Integer = Session("UserId")
                Dim _CertifiedId As Integer = p.CertifiedID
                _data.uspCertifiedHouseHouseUpdate(_UserId, _CertifiedId)
                Dim strLog As String = "Giay CN:" & txtCertifiedCode.Text.Trim() & ", tên hộ: " & p.Biz_VietName & ", nguoi dai dien: " & p.Ow_Name & ", CMND: " & p.Ow_CardID _
                                    & ", địa chỉ kinh doanh: " & p.Biz_HeadOffice & " huyen: " & p.ProvinceId.ToString & "userid: " & _UserId.ToString
                Insert_App_Log("Tạo  Certified:" & strLog & "", Function_Name.CertifiedHousehold, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))


                Excute_Javascript("Alertbox('Thêm mới dữ liệu thành công.');window.location ='../../Page/TiepNhan/Detail.aspx?Certifiedid=" & p.CertifiedID & "';", Me.Page, True)

            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/TiepNhan/List.aspx';", Me.Page, True)
            End Try

        End Using
    End Sub

    Protected Sub InsertCertified2nd()
        Using _data As New VSEntities
            Dim p As New VSModel.CertifiedHousehold
            Try
                'Thông tin chung
                p.CertifiedStatus = "D" 'cấp mới
                Dim _cNew = (From q In _data.CertifiedHouseholds Where q.CertifiedCode = txtCertifiedCode.Text.Trim() And q.ProvinceId = hidCurHuyenId.Value Order By q.CertifiedUp_Time Descending Select q).FirstOrDefault
                If Not _cNew.CertifiedUp_Time Is Nothing Then
                    p.CertifiedUp_Time = _cNew.CertifiedUp_Time + 1 'cấp mới = 0
                Else
                    p.CertifiedUp_Time = 0 'cấp mới = 0
                End If

                p.CertifiedCode = txtCertifiedCode.Text.Trim() ' số GCN
                p.CertifiedDate = StringToDate(txtCertifiedDate.Text) 'Ngày cấp GCN

                p.CertifiedUp_Date = Now 'ngay nhap ho so
                'thong tin ca nhan
                p.Ow_Name = txtOwRepresentative.Text 'Họ tên
                p.Ow_Sex = rdlSex.SelectedValue 'giới tính
                p.Ow_BirthDate = txtOwDateOfBirth.Text 'ngày tháng năm sinh
                p.Ow_National_ID = ddlCitizen.Text 'dân tộc
                p.Ow_Nationality_ID = ddlCountry.Text 'Quốc tịch
                p.Ow_CardID = txtOwCardId.Text 'Số CMND
                p.Ow_CardDate = StringToDate(txtOwCardDate.Text) 'Ngày cấp
                p.Ow_Provider_ID = ddlDeptCertified.Text 'Nơi cấp
                'giay to khac
                p.Ow_Doc_ID = ddlOthersPaper.SelectedValue 'Giấy tờ khác
                p.Ow_DocCode = txtOtherPaperCode.Text 'Mã số
                p.Ow_DocDate = StringToDate(txtOthersPaperDateIssue.Text.Trim()) 'Ngày cấp
                p.Ow_DocOffiCertifiedID = ddlOthersPaper_NoiCap.SelectedValue 'Nơi cấp
                'Thông tin hộ kinh doanh: 
                p.Biz_VietName = txtBizName.Text.Trim() 'Tên hộ kinh doanh
                p.Ow_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Ow_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Ow_Email = txtOw_Email.Text.Trim() 'Email
                p.Ow_WebSite = txtOw_WebSite.Text.Trim() 'Website
                p.Biz_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Biz_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Biz_Email = txtOw_Email.Text.Trim() 'Email
                p.Biz_Website = txtOw_WebSite.Text.Trim() 'Website
                'linh vưc
                p.LinhVucKinhDoanh = ddlBusinessField.Text 'Lĩnh vực kinh doanh
                p.VonTienMat = txtVonTienMat.Text.Trim()
                p.VonTaiSan = txtVonTaiSan.Text.Trim()
                p.Biz_InvestCapital = txtBiz_InvestCapital.Text.Trim().Replace(".", "") 'vốn kinh doanh
                p.Biz_WordsMoney = txtMoney_string.Text.Trim() 'Tiền viết bằng chữ
                p.Created = Now
                p.Creator = Session("UserName")
                Dim _StatusId As String = TinhTrangHoSo.Hoantat
                If Not _StatusId Is Nothing Then
                    p.StatusId = TinhTrangHoSo.Hoantat ' đã duyệt hồ sơ
                Else
                    p.StatusId = 1
                End If

                p.NguonTao = NguonTao.PhongTCKH
                p.ProvinceId = Session("HuyenId") ' Huyên đang ký kinh doanh
                'luu thong tin bien nhan 
                Dim _HuyenObj = (From q In _data.Provinces Where q.Id = _HuyenId Select q).FirstOrDefault
                If Not _HuyenObj Is Nothing Then
                    Dim _SoNgayTraHoSo As Integer
                    If StringToDateTime(Now.ToString("dd/MM/yyyy"), _HuyenObj.GioBienNhan) > Now Then
                        _SoNgayTraHoSo = _HuyenObj.SoNgayTraHoSo - 1
                    Else
                        _SoNgayTraHoSo = _HuyenObj.SoNgayTraHoSo
                    End If
                    p.NgayTraHoSo = _data.uspGetNumDateDelivery(Now.Date, _SoNgayTraHoSo).FirstOrDefault.DeliveryDate
                End If
                _data.CertifiedHouseholds.AddObject(p)
                _data.SaveChanges()
                Dim _cNewBegin = (From q In _data.CertifiedHouseholds Where q.CertifiedCode = txtCertifiedCode.Text.Trim() And q.ProvinceId = hidCurHuyenId.Value Order By q.CertifiedUp_Time Ascending Select q).FirstOrDefault
                If Not _cNewBegin.ParentId Is Nothing Then
                    p.ParentId = _cNewBegin.CertifiedID 'hồ sơ cấp đổi
                Else
                    p.ParentId = p.CertifiedID ' ho so dang ky lan parentId = CerId
                End If
                'Đơn vị cấp
                p.CertifiedProviderOrg = ddlCertifiedProviderOrg.SelectedValue
                'Phòng ban cấp
                p.CertifiedDeptName = ddlCertifiedDeptName.SelectedValue
                _data.SaveChanges()

                'Địa chỉ phường xa huyên
                Dim tht As New VSModel.CertifiedHouseholdAddress
                'thường trú
                tht.CertifiedID = p.CertifiedID
                tht.TypeId = LoaiDiaChi.ThuongTru
                tht.Adress = txtDiaChiHoKhau.Text.Trim()
                tht.TinhId = ddlTinhHoKhau.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                tht.HuyenId = hidHuyenHoKhau.Text
                tht.XaThiTranId = hidXaThiTranHoKhau.Text
                _data.CertifiedHouseholdAddresses.AddObject(tht)
                _data.SaveChanges()
                'luu thuong tru vao CertifiedHousehold
                'lay tien cac truong theo value
                'xa
                Dim jx = (From q In _data.Provinces Where q.Id = hidXaThiTranHoKhau.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jh = (From q In _data.Provinces Where q.Id = hidHuyenHoKhau.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jt = (From q In _data.Provinces Where q.Id = ddlTinhHoKhau.SelectedValue Select q.Title).FirstOrDefault
                p.Ow_Resident = txtDiaChiHoKhau.Text.Trim() & ", " & jx & ", " & jh & ", " & jt
                _data.SaveChanges()
                'tam trú
                Dim tt As New VSModel.CertifiedHouseholdAddress
                tt.CertifiedID = p.CertifiedID
                tt.TypeId = LoaiDiaChi.TamTru
                tt.Adress = txtDiaChiHienTai.Text.Trim()
                tt.TinhId = ddlTinhHienTai.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                tt.HuyenId = hidHuyenHienTai.Text
                tt.XaThiTranId = hidXaThiTranHienTai.Text
                _data.CertifiedHouseholdAddresses.AddObject(tt)
                _data.SaveChanges()
                'luu tam tru vao certifiedhousehold
                'lay tien cac truong theo value
                'xa
                Dim jxt = (From q In _data.Provinces Where q.Id = hidXaThiTranHienTai.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jht = (From q In _data.Provinces Where q.Id = hidHuyenHienTai.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jtt = (From q In _data.Provinces Where q.Id = ddlTinhHienTai.SelectedValue Select q.Title).FirstOrDefault
                p.Ow_Present = txtDiaChiHienTai.Text.Trim() & ", " & jxt & ", " & jht & ", " & jtt
                'địa điểm kinh doanh
                Dim kd As New VSModel.CertifiedHouseholdAddress
                kd.CertifiedID = p.CertifiedID
                kd.TypeId = LoaiDiaChi.DiaDiemKinhDoanh
                kd.Adress = txtBiz_HeadOffice.Text.Trim()
                kd.TinhId = ddlTinhDiaDiemKD.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                kd.HuyenId = hidHuyenDiaDiemKD.Text
                kd.XaThiTranId = hidXaThiTranDiaDiemKD.Text
                _data.CertifiedHouseholdAddresses.AddObject(kd)
                _data.SaveChanges()
                'luu dia diem kinh doanh vao certifiedhousehold
                'lay tien cac truong theo value
                'xa
                Dim jxd = (From q In _data.Provinces Where q.Id = hidXaThiTranDiaDiemKD.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jhd = (From q In _data.Provinces Where q.Id = hidHuyenDiaDiemKD.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jtd = (From q In _data.Provinces Where q.Id = ddlTinhDiaDiemKD.SelectedValue Select q.Title).FirstOrDefault
                p.XaPhuongId = hidXaThiTranDiaDiemKD.Text ' luu XaPhuongId de report

                p.Biz_HeadOffice = txtBiz_HeadOffice.Text.Trim() & ", " & jxd & ", " & jhd & ", " & jtd
                'start ngành nghề

                'lưu thông tin cho CertifiedHouseholdNganhNghe
                Try
                    Dim index As Integer = 0
                    Dim GrossAmount As Integer = 0
                    For i As Integer = 0 To hidRowIndex.Value - 1
                        Dim strMaterialCode As String = ""
                        Dim strMaterialDescription As String = ""
                        Dim strUnit As String = ""
                        Dim intAmount As Integer = 0

                        Dim txtMaterialCode As String = "txtChoice" + i.ToString
                        If Request.Form(txtMaterialCode) <> Nothing AndAlso Request.Form(txtMaterialCode).ToString.Trim() <> "" Then
                            strMaterialCode = Request.Form(txtMaterialCode)
                        End If

                        Dim txtMaterialDescription As String = "txtDescription" + i.ToString
                        If Request.Form(txtMaterialDescription) <> Nothing AndAlso Request.Form(txtMaterialDescription).ToString.Trim() <> "" Then
                            strMaterialDescription = Request.Form(txtMaterialDescription)
                        End If

                        If (strMaterialCode.Trim <> "") Then
                            Dim _NganhNgheId As Integer = (From q In _data.DanhMucNganhNghes Where q.Code = strMaterialCode Select q.Id).FirstOrDefault

                            Dim NganhNgheList As New CertifiedHouseholdNganhNghe
                            NganhNgheList.CertifiedID = p.CertifiedID
                            NganhNgheList.DanhMucNganhNgheID = _NganhNgheId
                            NganhNgheList.Description = strMaterialDescription

                            _data.CertifiedHouseholdNganhNghes.AddObject(NganhNgheList)

                            _data.SaveChanges()
                            index = index + 1

                            'End If
                        End If
                    Next
                Catch ex As Exception
                    Excute_Javascript("Alertbox('Cập nhật ngành nghề thất bại.');", Me.Page, True)
                    Exit Sub
                End Try
                'end ngành nghề
                'start danh sách góp vốn
                'lưu thông tin cho CertifiedHouseholdMember
                Try
                    Dim index As Integer = 0
                    For i As Integer = 0 To hidRowIndex1.Value - 1
                        Dim strTenTV As String = ""
                        Dim strNoiDKHK As String = ""
                        Dim strVonGop As String = ""
                        Dim strTyLeVonGop As String = ""
                        Dim strCMND As String = ""
                        Dim strDescription As String = ""

                        Dim txtTenTV As String = "txtTenTV__" + i.ToString
                        If Request.Form(txtTenTV) <> Nothing AndAlso Request.Form(txtTenTV).ToString.Trim() <> "" Then
                            strTenTV = Request.Form(txtTenTV)
                        End If

                        Dim txtNoiDKHK As String = "txtNoiDKHK__" + i.ToString
                        If Request.Form(txtNoiDKHK) <> Nothing AndAlso Request.Form(txtNoiDKHK).ToString.Trim() <> "" Then
                            strNoiDKHK = Request.Form(txtNoiDKHK)
                        End If
                        Dim txtVonGop As String = "txtVonGop__" + i.ToString
                        If Request.Form(txtTenTV) <> Nothing AndAlso Request.Form(txtVonGop).ToString.Trim() <> "" Then
                            strVonGop = Request.Form(txtVonGop)
                        End If

                        Dim txtTyLeVonGop As String = "txtTyLeVonGop__" + i.ToString
                        If Request.Form(txtTyLeVonGop) <> Nothing AndAlso Request.Form(txtTyLeVonGop).ToString.Trim() <> "" Then
                            strTyLeVonGop = Request.Form(txtTyLeVonGop)
                        End If
                        Dim txtCMND As String = "txtCMND__" + i.ToString
                        If Request.Form(txtCMND) <> Nothing AndAlso Request.Form(txtCMND).ToString.Trim() <> "" Then
                            strCMND = Request.Form(txtCMND)
                        End If

                        Dim txtDescription As String = "txtDescription__" + i.ToString
                        If Request.Form(txtDescription) <> Nothing AndAlso Request.Form(txtDescription).ToString.Trim() <> "" Then
                            strDescription = Request.Form(txtDescription)
                        End If

                        If (strTenTV.Trim <> "") Then

                            Dim member As New CertifiedHouseholdMember
                            member.CertifiedID = p.CertifiedID
                            member.MemberName = strTenTV
                            member.MemberAddress = strNoiDKHK
                            member.MemberValues = strVonGop
                            member.MemberRate = strTyLeVonGop
                            member.MemberCard = strCMND
                            member.MemberDes = strDescription
                            member.MemberOrder = member.Id
                            _data.CertifiedHouseholdMembers.AddObject(member)

                            _data.SaveChanges()
                            index = index + 1

                            'End If
                        End If
                    Next
                Catch ex As Exception
                    Excute_Javascript("Alertbox('Cập nhật danh sách góp vốn thất bại.');", Me.Page, True)
                    Exit Sub
                End Try
                'end danh sách góp vốn

                'start thành phần hồ sơ
                Dim intId As Integer = 0
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        'lay id cua thanh phan ho so
                        intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                        Dim ThanhPhanHoSo As New CertifiedHouseholdThanhPhanHoSo
                        ThanhPhanHoSo.CertifiedID = p.CertifiedID
                        ThanhPhanHoSo.ThanhPhanHoSoId = intId
                        _data.CertifiedHouseholdThanhPhanHoSoes.AddObject(ThanhPhanHoSo)
                        _data.SaveChanges()
                    End If
                Next

                'correct lai Province + HuyenId
                Dim _UserId As Integer = Session("UserId")
                Dim _CertifiedId As Integer = p.CertifiedID
                _data.uspCertifiedHouseHouseUpdate(_UserId, _CertifiedId)
                Dim strLog As String = "Giay CN:" & txtCertifiedCode.Text.Trim() & ", tên hộ: " & p.Biz_VietName & ", nguoi dai dien: " & p.Ow_Name & ", CMND: " & p.Ow_CardID _
                                    & ", địa chỉ kinh doanh: " & p.Biz_HeadOffice & " huyen: " & p.ProvinceId.ToString & "userid: " & _UserId.ToString
                Insert_App_Log("Tạo  Certified:" & strLog & "", Function_Name.CertifiedHousehold, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))


                Excute_Javascript("Alertbox('Thêm mới dữ liệu thành công.');window.location ='../../Page/TiepNhan/Detail.aspx?Certifiedid=" & p.CertifiedID & "';", Me.Page, True)

            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/TiepNhan/List.aspx';", Me.Page, True)
            End Try

        End Using
    End Sub
#End Region

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            'so sanh tren code cua GCN 
            Dim checkCode As String = Nothing
            If Not chkBangHieu.Checked Then
                checkCode = (From q In data.CertifiedHouseholds Where q.Biz_VietName = txtBizName.Text.Trim() And q.ProvinceId = hidCurHuyenId.Value Select q.Ow_Name).FirstOrDefault
            End If

            If Not checkCode Is Nothing Then
                Excute_Javascript("Alertbox('Tên hộ kinh doanh đã tồn tại trong hệ thống.')", Me.Page, True)
                Exit Sub
            End If
            If rdoCapMoi.Checked Then
                InsertCertified()
            ElseIf rdoCapDoi.Checked Then
                'lưu bản ghi cấp mới
                InsertCertified()
                'lưu bản ghi cấp đổi theo số lần
                For _i As Integer = 1 To ddlSoLanCapDoi.SelectedValue
                    InsertCertified2nd()
                Next
            End If
        End Using
    End Sub

    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub
#End Region

    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = e.Row.RowIndex + 1
            If Not grdShow.DataKeys(e.Row.RowIndex)("IsDefault") Is Nothing Then
                Dim chkItem As CheckBox = e.Row.FindControl("chkItem")
                chkItem.Checked = grdShow.DataKeys(e.Row.RowIndex)("IsDefault")
            End If
        End If
    End Sub
End Class
